<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="never">
          <TreeModule @change="treeChange"/>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card shadow="never">
          <vxe-grid v-bind="gridOptions" v-on="gridEvents" ref="xGrid">
            <!-- 表单 start -->
            <template #actionItem>
              <el-button
                color="#1E3485"
                size="small"
                icon="Edit"
                @click=" EditDialogModal.open({type: 'add',row: {} , treeRow: treeRow})"
              >新建</el-button>
              <el-button
                size="small"
                color="#1E3485"
                icon="Search"
                @click="searchChange"
              >搜索</el-button>
              <el-button
                size="small"
                type="default"
                icon="Delete"
                @click="searchReset"
              >清空</el-button>
              <el-button
                size="small"
                type="info"
                icon="Setting"
                @click="resetPassword"
              >密码重置</el-button>
            </template>
            <!-- 表单 end -->

            <!-- 表格 start -->
            <template #menu="{ row }">
              <vxe-button
                type="text"
                size="small"
                @click="EditDialogModal.open({type: 'view',row, treeRow: treeRow})"
              >
                查看
              </vxe-button>
              <vxe-button
                type="text"
                size="small"
                @click="EditDialogModal.open({type: 'edit',row, treeRow: treeRow})"
              >
                编辑
              </vxe-button>
              <vxe-button
                type="text"
                size="small"
                @click="rowDel(row)"
              >
                删除
              </vxe-button>
            </template>
            <!-- 表格 end -->
          </vxe-grid>
        </el-card>
      </el-col>
    </el-row>


    <EditDialog
      @register="EditDialogModal.register"
      @confirmRowAdd="rowAdd"
      @confirmRowEdit="rowEdit"
      />
  </div>
</template>

<script lang="ts" setup>
  import {getCurrentInstance, reactive, ref} from 'vue'
import type { VxeGridProps, VxeGridListeners, VxeFormInstance } from 'vxe-table'
import EditDialog, { useEditDialog } from './components/EditDialog'
import TreeModule from './components/TreeModule/index.vue'
import {getSettings} from "./settings";
  import { getOrgMenberList } from "@/api/ERP_sales";
  import {
    userSync,
    passwordReset,
    getPasswordDefault,
    userSave, userDelete
  } from "@/api/ERP_baseMessage";
import { ElMessage, ElMessageBox } from 'element-plus'

const EditDialogModal = useEditDialog()

  const treeRow = ref({})
function treeChange(node) {
  treeRow.value = node
  gridOptions.formConfig.data.deptId = node.id
  getList()
}


// 前端分页
const getList = async () => {
  if(gridOptions.loading) return
  gridOptions.loading = true
  console.log(gridOptions.formConfig.data)
  const params: ApiParams = {
    pageIndex: gridOptions.pagerConfig.currentPage,
    pageSize: gridOptions.pagerConfig.pageSize,
    ...gridOptions.formConfig.data,
  };

  try {
    const response: ApiResponse = await getOrgMenberList(params);
    gridOptions.data = response.data.records;
    gridOptions.pagerConfig.total = response.data.totalElements;
  } catch (error) {
    ElMessage.error("获取表格数据失败");
  } finally {
    gridOptions.loading = false;
  }
}
const xGrid = ref<VxeFormInstance>()
const gridOptions = reactive<VxeGridProps<RowVO>>({
  ...getSettings(),
  data: [],
})

const instance = getCurrentInstance()
const globalThis = instance.appContext.config.globalProperties
const resetPassword = async () => {
  const $xGrid = xGrid.value
  const list  = $xGrid.getCheckboxRecords()
  if(list.length === 0) {
    globalThis.$message.warning('请选择至少一条数据')
    return
  }
  const passWord = '接口数据'
  const data = await getPasswordDefault()
  console.log(data)
  await globalThis.$confirm(
    `确定将选择账号密码重置为${passWord}?`,
    {
      title: '提示',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  await passwordReset({
    idList: list
  })
  globalThis.$message.success('重置成功')
  getList()
}
  const rowAdd = async (form = {}, row = {}, done, loading) => {
    console.log(form, row)
    try {
      await userSave({
        ...form
      })
      done()
      getList()
    }catch (e) {
      console.log(e)
      loading()
    }
  }
  const rowEdit = async (form = {},  row = {}, done, loading) => {
    console.log(form, row)
    try {
      const {parentId,deptCategory, deptLevel, sort, shortName, deptCode, deptName } = form
      const {parentCode,id } = row
      const params = {
        id,
        parentCode,
        parentId,
        deptCategory,
        deptLevel,
        sort,
        shortName,
        deptCode,
        deptName,
      }
      await userSync(params)
      done()
      getList()
    }catch (e) {
      console.log(e)
      loading()
    }
  }
  const rowDel = async (row) => {
    try {
      await globalThis.$confirm(
        `确认删除选中的数据吗？`,
        {
          title: '提示',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      await userDelete({
        id: row.id
      })
      globalThis.$message.success('删除成功')
      getList()
    } catch (e) {
      console.log(e)
    }
  }


const searchChange = () => {
  gridOptions.pagerConfig.currentPage = 1
  getList()
}
const searchReset = () => {
  const $xGrid = xGrid.value
  const $form = $xGrid.getRefMaps().refForm.value
  if ($form) {
    $form.reset()
  }
  gridOptions.pagerConfig.currentPage = 1
  gridOptions.pagerConfig.pageSize = 10
  getList()
}


const gridEvents: VxeGridListeners = {
  pageChange ({ pageSize, currentPage }) {
    gridOptions.pagerConfig.currentPage = currentPage
    gridOptions.pagerConfig.pageSize = pageSize
    getList()
  },
  formReset() {
    console.log('reset')
  }
}
getList()
</script>
